<?php

namespace app\jigou\controller\qingdongams\customer;

use app\jigou\controller\qingdongams\Base;
use addons\qingdongams\model\CustomerProduct;
use fast\Random;
use think\Db;
use think\Exception;

/**
 * 设备
 * @icon fa fa-user
 */
class Equipment extends Base {
	protected $relationSearch = true;
//	protected $searchFields   = 'id,username,nickname';
	/**
	 * @var \addons\qingdongams\model\Equipment
	 */
	protected $model = null;
    protected $proModel = null;
    protected $productList = null;
    protected $customerProductModel = null;
    protected $customerProductList = null;


	public function _initialize() {
		parent::_initialize();
		$this->model = new \addons\qingdongams\model\Equipment;
		$this->proModel = new \addons\qingdongams\model\Product();
		$this->customerProductModel = new CustomerProduct();

        $this->productList = collection($this->proModel->select())->toArray();
        $productList = [0 => __('None')];
        foreach ($this->productList as $k => &$v) {
            $productList[$v['id']] = $v['name'];
        }
        $this->customerProductList = collection($this->customerProductModel->select())->toArray();
        $customerProductList = [0 => __('None')];
        foreach ($this->customerProductList as $k => &$v) {
            $customerProductList[$v['id']] = $v['number'];
        }
        $this->view->assign('productList', $productList);
        $this->view->assign('customerProductList', $customerProductList);
	}

    /**
     * 列表
     */
    public function lists($ids = null) {
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list   = $this->model->where([
            'pro_id' => $ids,
        ])->paginate($limit);
        $result = array("total" => $list->total(), "rows" => $list->items());
        return json($result);
    }



    /**
	 * 查看
	 */
	public function index() {
		//设置过滤方法
		$this->request->filter(['strip_tags', 'trim']);
		if ($this->request->isAjax()) {
			list($where, $sort, $order, $offset, $limit) = $this->buildparams();
//
			//负责人为空
			$list = $this->model->where([])->where($where)->with('product')->order('id', 'desc')->paginate($limit);

			$result = array("total" => $list->total(), "rows" => $list->items());

			return json($result);
		}
		return $this->view->fetch();
	}


	/**
	 * 添加
	 */
	public function add() {
		if ($this->request->isPost()) {
			$params = $this->request->post("row/a");
			if ($params) {
				$params = $this->preExcludeFields($params);
				$result = false;
				Db::startTrans();
				try {
				    $productModel = new \addons\qingdongams\model\Product();
				    $proName = $productModel->where(['id'=>$params['pro_id']])->value('name');
				    $params['number'] = date("md").rand(100000,999999);
                    $img = $proName.'_'.$params['number'];
                    if(create_logo_qrcode($img) == 'ok'){
					    $params['logo'] = "/qrcode/".$img.'.jpg';
                    }else{
                        throw new \Exception('二维码生成有误');
                    }
                    $params['binding_status'] = 1;
					$result = $this->model->allowField(true)->save($params);
					Db::commit();
				} catch (Exception $e) {
					Db::rollback();
					$this->error($e->getMessage());
				}
				if ($result !== false) {
					$this->success();
				} else {
					$this->error(__('No rows were inserted'));
				}
			}
			$this->error(__('Parameter %s can not be empty', ''));
		}
		return $this->view->fetch();
	}

    /**修改
     */
	public function edit($ids = null) {
		$map['id'] = $ids;
		if ($this->request->isAjax()) {
			$params = $this->request->post('row/a');
			$params = $this->preExcludeFields($params);
			$result = false;
			Db::startTrans();
			try {
			    unset($params['logo']);
			    unset($params['number']);
				$result = $this->model->allowField(true)->update($params, $map);
				Db::commit();
			} catch (Exception $e) {
				Db::rollback();
				$this->error($e->getMessage());
			}
			if ($result !== false) {
				$this->success('修改成功');
			} else {
				$this->error('修改失败');
			}
		}
		$data = $this->model->where($map)->find();
		$this->view->assign("row", $data);

		return $this->view->fetch();
	}

    /**详情
     */
	public function detail($ids=null){
		$row=$this->model->get($ids);
		$this->assign('row',$row);
		$this->assign('ids',$ids);
		return $this->view->fetch();
	}

	/**
	 * 删除
	 */
	public function del($ids = "") {
		if (!$this->request->isPost()) {
			$this->error(__("Invalid parameters"));
		}
		$ids                 = $ids ? $ids : $this->request->post("ids");
		$ids = explode(',',$ids);
        $this->model->destroy(function ($query) use($ids){
            $query->where('id','in',$ids);
        });
		$this->success();
	}

    /**
     * 导出二维码 -- 格式为所有二维码图片
     * @param $ercode_list 二维码链接数组，我的数组包含两个参数，url 和 unique_id
     * 			url 二维码链接
     * 			unique_id 主要为生成独一无二的二维码文件名称
     * @return string
     */
    public function export_ercode()
    {


        $ids = $this->request->get('ids');
        $ercode_list = collection($this->model->where('id','in',explode(',',$ids))->select())->toArray();
        $img_arr = array();
        foreach ($ercode_list as $ercode) {
            $img_name = ROOT_PATH."public".$ercode['logo'];
            $img_arr[] = $img_name;
        }
        $zip_name = ROOT_PATH.'public/uploads/ercode/ercode_' . date('YmdHis') . '.zip';
        makeZip($zip_name, $img_arr);
        download($zip_name);

        $this->redirect('index');

    }
}
